import * as dateFns from 'date-fns'
import { defaultsDeep } from 'lodash'
import config from '@/utils/config/index.js'
import { queryUnreadMsgCount, saveCpisBusinessOpLog, getLatestAppVersion } from '@/api/platform/common.js'
import * as sqliteUtil from '@/utils/sqlite.js'
import project from '@/utils/config/project.js'

//通知消息
const notice = {
	toast(title, duration = 2000) {
		uni.showToast({
			title,
			duration,
			icon: 'none'
		});
	},
	success(title, duration = 2000) {
		uni.showToast({
			title,
			duration
		});
	},
	fail(title, duration = 2000) {
		uni.showToast({
			title,
			duration,
			icon: 'none'
		});
		// uni.showToast({
		// 	title,
		// 	image:'/static/images/icon/warn-icon.png',
		// 	icon: 'none'
		// });
	},
	showLoading(title = '请稍后') {
		uni.showLoading({
			title,
			mask: true
		})
	},
	hideLoading() {
		uni.hideLoading()
	},
	alert(content, callback) {
		uni.showModal({
			content,
			confirmColor: constant.APP_DEFAULT_COLOR,
			showCancel: false,
			success() {
				callback && callback()
			}
		})
	},
	/**
	 * @param {Object} opt 
	 * content 内容 ，title 标题 ，cancelText 取消文本文字 confirmText 确认文字
	 * success 成功回调 
	 */
	confirm(content, ok, cancel, opt = {}) {
		const nOpt = Object.assign(opt, {
			cancelColor: constant.APP_DEFAULT_COLOR,
			confirmColor: constant.APP_DEFAULT_COLOR,
			content
		});
		nOpt.success = function(res) {
			if (res.confirm) ok && ok();
			else cancel && cancel();
		}
		uni.showModal(nOpt);
	}
}

// 公共
const utilities = {
	//得到当前日期时间
	getNowDateTime() {
		return dateFns.format(new Date(), 'yyyy-MM-dd HH:mm:ss')
	},
	//得到当前日期
	getNowDate() {
		return dateFns.format(new Date(), 'yyyy-MM-dd')
	},
	//日期时间计算
	getCalDateTime(start, num) {
		return dateFns.format(dateFns.addHours(new Date(start), num), 'yyyy-MM-dd HH:mm:ss')
	},
	//日期时间格式化
	formatDateTime(dateObj, dateFormat = 'yyyy-MM-dd HH:mm:ss') {
		return dateFns.format(new Date(dateObj), dateFormat)
	},
	//格式化时间
	formatTime(time) {
		if (typeof time !== 'number' || time < 0) {
			return time
		}
	
		var hour = parseInt(time / 3600)
		time = time % 3600
		var minute = parseInt(time / 60)
		time = time % 60
		var second = time
	
		return ([hour, minute, second]).map(function (n) {
			n = n.toString()
			return n[1] ? n : '0' + n
		}).join(':')
	},
	// 转换菜单为树形结构
	transformToTreeFormat(data, setting = {}) {
		const defaultSetting = {
			isParent: 'isParent',
			childrenKey: 'children',
			nameKey: 'name',
			titleKey: 'title',
			idKey: 'id',
			pIdKey: 'parentId',
			levelKey: 'level',
			rootPId: null
		}
	    const sNodes = JSON.parse(JSON.stringify(data))
	    setting = defaultsDeep({}, setting, defaultSetting)
	    const idKey = setting.idKey
	    const pIdKey = setting.pIdKey
	    const childrenKey = setting.childrenKey
	
	    let i, j, l
	    if (!idKey || idKey === '' || !sNodes) { 
			return [] 
		}
	    if (sNodes instanceof Array) {
			const r = []
			const tmpMap = []
			for (i = 0, l = sNodes.length; i < l; i++) {
				tmpMap[sNodes[i][idKey]] = sNodes[i]
			}
	
			for (j = 0, l = sNodes.length; j < l; j++) {
				if (tmpMap[sNodes[j][pIdKey]] && sNodes[j][idKey] !== sNodes[j][pIdKey]) {
					if (!tmpMap[sNodes[j][pIdKey]][childrenKey]) {
						tmpMap[sNodes[j][pIdKey]][childrenKey] = []
					}
					tmpMap[sNodes[j][pIdKey]][childrenKey].push(sNodes[j])
				} else {
					r.push(sNodes[j])
				}
			}
			return r
	    } else {
			return [sNodes]
	    }
	},
	/**
	 * 返回方法说明：
	 * type：online--在线消息，offline--离线消息，msg--消息模块，flow--流程待办，'back'--页面返回, ''--业务返回
	 * 1、在线消息/离线消息：不刷新列表
	 * 	1.1 在线消息：返回上一页
	 * 	1.2 离线消息：返回首页
	 * 2、消息模块/流程待办/业务返回：刷新列表，返回上一页
	 * 3、页面返回：不做处理
	 */
	//延时返回
	back(type, index) {
		setTimeout(function(){
			if(type == 'offline') {
				uni.switchTab({
					url: '/pages/platform/home/index'
				})
			}
			if(type != 'online' && type != 'offline' && type != 'back') {
				var pages = getCurrentPages();
				var prevPage = pages[pages.length - 2]; //上一个页面
				prevPage.$vm.reload(!index ? 0 : index);
				uni.navigateBack();
			}
		}, 1000)
	},
	//立即返回
	backQuick(type, index) {
		if(type == 'offline') {
			uni.switchTab({
				url: '/pages/platform/home/index'
			})
		} 
		if(type != 'online' && type != 'offline' && type != 'back') {
			var pages = getCurrentPages();
			var prevPage = pages[pages.length - 2]; //上一个页面
			prevPage.$vm.reload(!index ? 0 : index);
			uni.navigateBack();
		}
	},
	//自定义层数返回
	backMore(index, layer) {
		var pages = getCurrentPages();
		var prevPage = pages[pages.length - layer - 1]; //上一个页面
		prevPage.$vm.reload(!index ? 0 : index);
		uni.navigateBack({
		    delta: layer
		});
	},
	//物资专用返回方法
	backStock(type) {
		if(type == 'offline') {
			uni.switchTab({
				url: '/pages/platform/home/index'
			})
		} 
		if(type != 'online' && type != 'offline' && type != 'back') {
			var pages = getCurrentPages();
			var prevPage = pages[pages.length - 2]; //上一个页面
			prevPage.$vm.loadData(true);
			uni.navigateBack();
		}
	},
	// 获取配置项值
	getConfig(name) {
		return config[name]
	},
	// 下划线转驼峰
	fieldToHump(data) {
		const that = this
		data.forEach(function(item, index, arr) {
			arr.splice(index, 1, that.convert(item))
		})
	},
	// 下划线转驼峰
	convert(data) {
		if (typeof data !== 'object' || !data) return data
		if (Array.isArray(data)) {
			return data.map(item => this.convert(item))
		}
	
		let newObj = {}
		for (const key in data) {
			if (Object.prototype.hasOwnProperty.call(data, key)) {
				let newKey = key.replace(/_([a-z])/g, res => res[1].toUpperCase())
				newObj[newKey] = this.convert(data[key] == 'null' ? null : data[key] == 'undefined' ? '' : data[key])
			}
		}
		return newObj
	},
	/**
	 * 数据对象key 驼峰下划线互相转化
	 * @param {Object} data 需要转换的对象
	 * @param {String} type hump-转驼峰 line-转下划线
	 */
	formatHumpLineTransfer(data, type = 'hump') {
		// 字符串下划线转驼峰
		const formatToHump = (value) => {
			return value.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())
		}
		
		// 字符串驼峰转下划线
		const formatToLine = (value) => {
			return value.replace(/([A-Z])/g, '_$1').toLowerCase()
		}
		
		let hump = ''
		// 转换对象中的每一个键值为驼峰的递归
		const formatTransferKey = (data) => {
			if (Array.isArray(data)) {
				data.forEach(item => formatTransferKey(item))
			} else if (Object.prototype.toString.call(data) === '[object Object]') {
				for (const key in data) {
					hump = type === 'hump' ? formatToHump(key) : formatToLine(key)
					data[hump] = data[key] == 'null' ? null : data[key] == 'undefined' ? '' : data[key]
					if (key !== hump) {
						delete data[key]
					}
					if (data[hump] instanceof Object) {
						formatTransferKey(data[hump])
					}
				}
			} else if (typeof data === 'string') {
				data = type === 'hump' ? formatToHump(data) : formatToLine(data)
			}
		}
		formatTransferKey(data)
		return data
	},
	// 获取版本
	async getAppVersion() {
		// 获取应用信息
		let applicationInfo = uni.getSystemInfoSync()
		// 当前版本
		let version = applicationInfo.appVersion
		uni.setStorageSync("currentVersion", version)
		// 操作系统
		let os = applicationInfo.osName
		// 查询最新版本信息
		let res = await getLatestAppVersion(os)
		let latestVersion = res.data ? res.data : {}
		uni.setStorageSync("latestVersion", latestVersion)
	},
	/**
	 * 对比版本号，如需要，请自行修改判断规则
	 * 支持比对	("3.0.0.0.0.1.0.1", "3.0.0.0.0.1")	("3.0.0.1", "3.0")	("3.1.1", "3.1.1.1") 之类的
	 * @param {Object} v1
	 * @param {Object} v2
	 * v1 > v2 return 1
	 * v1 < v2 return -1
	 * v1 == v2 return 0
	 */
	compareVersion(v1 = '0', v2 = '0') {
		v1 = String(v1).split('.')
		v2 = String(v2).split('.')
		const minVersionLens = Math.min(v1.length, v2.length);
	
		let result = 0;
		for (let i = 0; i < minVersionLens; i++) {
			const curV1 = Number(v1[i])
			const curV2 = Number(v2[i])
	
			if (curV1 > curV2) {
				result = 1
				break;
			} else if (curV1 < curV2) {
				result = -1
				break;
			}
		}
	
		if (result === 0 && (v1.length !== v2.length)) {
			const v1BiggerThenv2 = v1.length > v2.length;
			const maxLensVersion = v1BiggerThenv2 ? v1 : v2;
			for (let i = minVersionLens; i < maxLensVersion.length; i++) {
				const curVersion = Number(maxLensVersion[i])
				if (curVersion > 0) {
					v1BiggerThenv2 ? result = 1 : result = -1
					break;
				}
			}
		}
	
		return result
	},
	/**
	 * 数据分组
	 * @param arr [Array] 被处理的数组
	 * @param group_key [String] 分组字段
	*/
	formatDataGroup(arr, group_key) {
		var map = [{
			[group_key]: arr[0][group_key],
			item: [arr[0]],
		}]
		for (var i = 1; i < arr.length; i++) {
			let bool = map.some((it)=>{
				if(arr[i][group_key] == it[group_key]){
					it['item'].push(arr[i])
				}
				return (arr[i][group_key] == it[group_key])
			})
			if(!bool){
				map.push({
					[group_key]: arr[i][group_key],
					item: [arr[i]],
				})
			}
		}
		return map
	}
}

// 业务相关
const business = {
	//刷新消息数量
	refreshMsgCount() {
		queryUnreadMsgCount().then(res=>{
			const count = res.data || 0
			
			if(count > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: count < 100 ? count + '' : '99+'
				})
			} else {
				uni.removeTabBarBadge({
					index: 1
				})
			}
			
		})
	},
	// 处理流程错误(目前仅用于物资流程，以第一个中文字符开始截取)
	handleErr(resData) {
		let msg = resData.msg
		let str = resData.cause
		let len = str.length
		for (let i = 0; i < len; i++) {
		    if (str.charCodeAt(i) > 128) {
				msg = str.substring(i, len)
				break
			}
		}
		return msg
	},
	// 页面路径(动态URL)
	getPagePath(code) {
		let page = uni.getStorageSync("pagePathList").find(r => r.pageCode == code)
		if(page) {
			return page
		}
		return null
	},
	// 保存业务操作日志
	saveOpLog(operateType, businessKey, operateKey) {
	    let data = {
			userId: uni.getStorageSync("userId"),
			userName: uni.getStorageSync("userName"),
			fullName: uni.getStorageSync("userFullName"),
			companyId: uni.getStorageSync("companyId"),
			pageUrl: this.getPath(),
			operateType: operateType,
			businessKey: businessKey,
			operateKey: operateKey,
			systemKey: "00"
	    }
	    saveCpisBusinessOpLog(data)
	},
	getPath() {
		let curPage = getCurrentPages();
		//获取当前页面的路由
		let route = curPage[curPage.length - 1].route; 
		// //获取当前页面参数，如果有则返回参数的对象，没有参数返回空对象{}
		// let params = curPage[curPage.length - 1].options; 
		// //获取对象的key 返回对象key的数组
		// let keys = Object.keys(params); 
		
		// let query = '';
		// if (keys.length > 0) {
		// 	query = keys.reduce((pre, cur) => {
		// 		return pre + cur + '=' + params[cur] + '&';
		// 	}, '?').slice(0, -1);
		// }
		return route
	},
	handleCode(data) {
		if(data.indexOf("&") === -1) {
			notice.toast("二维码格式不正确")
			throw new Error("二维码格式不正确")
		}
		
		let ret = {
			scanType: '',
			scanId: '',
			scanNo: '',
			scanName: ''
		}
		if(project.NFC_OLD_CODE) {
			ret.scanId = data.split("&")[0].split("=")[1]
			ret.scanType = data.split("&")[1].split("=")[1]
		} else {
			let arr = data.split("&", 3)
			ret.scanType = arr[0].split("=")[1]
			ret.scanId = arr[1].split("=")[1]
			ret.scanNo = arr[2].split("=")[1]
			ret.scanName = data.substr(data.indexOf('NAME')+5)
		}
		return ret
	}
}

const file = {
	//图片预览
	previewImage(fileId) {
		return config.baseUrl + '/platform/v3/file/preview' + "?attachmentId=" + fileId
	},
	//图片展示
	showImage(fileId) {
		uni.previewImage({
			urls: [this.previewImage(fileId)]
		})
	},
	//是否为图片
	checkIsImg(attachment) {
		const fileExtension = attachment.ext
		return fileExtension === 'jpg' || fileExtension === 'jpeg' || fileExtension === 'png' || fileExtension === 'bmp' || fileExtension === 'gif'
	},
	//是否为音频
	checkIsAudio(attachment) {
		const fileExtension = attachment.ext
		return fileExtension === 'mp3' || fileExtension === 'amr'
	},
	//是否为视频
	checkIsVideo(attachment) {
		const fileExtension = attachment.ext
		return fileExtension === 'mp4' || fileExtension === 'flv'
	},
	//下载文件
	downFileUrl(fileId) {
		return config.baseUrl + '/platform/v3/file/download' + "?attachmentId=" + fileId 
	},
	//下载文件
	downloadFile(fileId, fileName){
		uni.showLoading({
			title: '附件下载中',
			mask: true
		})
		var dtask = plus.downloader.createDownload(this.downFileUrl(fileId), {
			filename: "_downloads/" + fileName //利用保存路径，实现下载文件的重命名
		}, function(d, status){
			if(status == 200){ 
				uni.hideLoading()
				var fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
				plus.runtime.openFile(d.filename); //选择软件打开文件
			} else {
				uni.hideLoading()
				console.log("Download failed: " + status); 
			}
		});
		dtask.start();
	},
	//上传文件
	uploadFile(filePath, files) {
		uni.showLoading({
			title: '附件上传中',
			mask: true
		})
		
		return new Promise((resolve, reject) => {
			const params = {
				// url: config.baseUrl + '/platform/v3/file/upload',
				url: config.baseUrl + '/extend/v3/file/uploadExtend',
				name: 'file',
				filePath,
				success: (res) =>{
					const data = JSON.parse(res.data)
					resolve(data.data)
					uni.hideLoading()
				},
				fail() {
					notice.toast('上传失败，请稍后再试')
					uni.hideLoading()
					reject()
				}
			}
			
			if(filePath) {
				params.filePath = filePath
			} else {
				params.files = files
			}
			
			uni.uploadFile(params)
		})
	},
	//上传文件--文件集
	uploadFileset(filePath, formData) {
		uni.showLoading({
			title: '附件上传中',
			mask: true
		})
		
		return new Promise((resolve, reject) => {
			const params = {
				url: config.baseUrl + '/extend/v3/DocumentCollection',
				name: 'file',
				filePath,
				formData,
				success: (res) =>{
					const data = JSON.parse(res.data)
					resolve(data.data)
					uni.hideLoading()
				},
				fail() {
					notice.toast('上传失败，请稍后再试')
					uni.hideLoading()
					reject()
				}
			}
			
			uni.uploadFile(params)
		})
	},
	//获取图片
	getImg(picture) {
		return config.baseUrl + '/platform/v3' + picture
	},
	//获取图片
	getImage(fileId) {
		return config.baseUrl + '/platform/v3/file/getImage?attachmentId=' + fileId
	},
	//获取文件大小
	getFileSize(originalSize){
		return parseFloat(originalSize/1024).toFixed(2)
	},
	//获取MIME类型
	getFileType(file) {
		let fileType
		switch(file.ext) {
			case "bmp":
				fileType = "image/bmp"
				break
			case "doc":
				fileType = "application/msword"
				break
			case "docx":
				fileType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
				break
			case "gif":
				fileType = "image/gif"
				break
			case "jpg":
				fileType = "image/jpeg"
				break
			case "jpeg":
				fileType = "image/jpeg"
				break
			case "mp3":
				fileType = "audio/mpeg"
				break
			case "mp4":
				fileType = "video/mp4"
				break
			case "pdf":
				fileType = "application/pdf"
				break
			case "png":
				fileType = "image/png"
				break
			case "ppt":
				fileType = "application/vnd.ms-powerpoint"
				break
			case "txt":
				fileType = "text/plain"
				break
			case "wps":
				fileType = "application/vnd.ms-works"
				break
			case "xls":
				fileType = "application/vnd.ms-excel"
				break
			case "xlsx":
				fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
				break
			case "zip":
				fileType = "application/zip"
				break
			default: 
				fileType = ""
		}
		return fileType
	},
	// 获取离线附件信息
	async getOfflineFile(fileId) {
		let file = await sqliteUtil.selectTableInfo('m_cpis_file_attachment', 'id', fileId)
		let fileInfo = {
			id: file[0].id,
			name: file[0].file_name,
			filePath: file[0].file_path,
			ext: file[0].ext
		}
		return fileInfo
	},
	/**
	 * APP端图片压缩
	 *  参数说明：
	 *  img 图片url
	 *  scale缩放比例 1-100
	 *  callback 回调设置返回值 
	*/
	compressImage(img, scale, callback) {
		// 通过URL参数获取目录对象或文件对象
		plus.io.resolveLocalFileSystemURL(img, (entry) => {
			// 可通过entry对象操作图片
			entry.file((file) => {
				// console.log('压缩前图片信息:' + JSON.stringify(file));
				
				// 如果大于500Kb进行压缩
				if (file.size > 504800) {
					// 5+ plus.zip.compressImage 了解一下，有详细的示例
					plus.zip.compressImage({
						// src: 压缩原始图片的路径
						src: img, 
						// dst: (String类型)压缩转换目标图片的路径，这里先在后面原始名后面加一个cp区分一下
						dst: img.replace('.png', '_compress.png').replace('.PNG', '_compress.PNG').replace('.jpg', '_compress.jpg').replace('.JPG', '_compress.JPG'),
						// width: (String类型)缩放图片的宽度
						// width: '40%',
						// height: (String类型)缩放图片的高度
						// height: '40%',
						// quality: (Number类型)压缩图片的质量
						quality: scale,
						// overwrite: (Boolean类型)覆盖生成新文件
						overwrite: true,
						// format: (String类型)压缩转换后的图片格式
						// format:'jpg'
					}, (event) => {
						// console.log('压缩后图片信息:' + JSON.stringify(event)); 
						
						//返回压缩后的图片路径
						callback(event.target);
					}, function(err) {
						console.log('Resolve file URL failed: ' + err.message);
					});
				} else { 
					// 小于500kb跳过压缩，直接返回现有的src
					callback(img);
				}
			});
		}, (e) => { 
			// 返回错误信息
			console.log('Resolve file URL failed: ' + e.message);
		});
	},
	/**
	 * APP端视频压缩
	 *  参数说明：
	 *  file 视频url
	 *  callback 回调设置返回值 
	*/
	compressVideo(file, callback) {
		plus.zip.compressVideo({
			// src: 压缩原始视频的路径
			src: file,
			// quality: 压缩质量
			quality: 'medium'
		}, (event) => {
			// console.log("压缩视频成功：" + JSON.stringify(event));
			plus.nativeUI.closeWaiting();
			//返回压缩后的视频路径
			callback(event.tempFilePath);
		}, function(err) {
			plus.nativeUI.closeWaiting();
			console.log('Resolve file URL failed: ' + err.message);
		});
	}
}

export {
	notice,
	utilities,
	business,
	file
}
